package org.xhnews.ui;

import java.util.Vector;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;

import org.xhnews.bo.ForwardBo;
import org.xhnews.to.MessageItem;

public class MessageListField extends ListField implements ListFieldCallback,ShowWindow {
	private Vector _messgelist;
	Bitmap readPic = Bitmap.getBitmapResource("read.png");
	public MessageListField() {
		_messgelist = new Vector();
		setRowHeight(getFont().getHeight()*2);
		setCallback(this);
		initialize();
	}

	public void initialize() {
		
		reload();
	}

	public void reload() {
		Vector messageitems = ForwardBo.getMessages();
		_messgelist = messageitems;
		setSize(_messgelist.size());
	}

	public void drawListRow(ListField list, Graphics g, int index, int y, int w) {
		MessageItem temp = (MessageItem) _messgelist.elementAt(index);
		String title = temp.getTitle();
		String  source= temp.getDate();
		String  pubDate= temp.getSenderName();
		if (!temp.isRead())
			g.drawBitmap(0, y + 2, 3, list.getRowHeight() - 2, readPic, 0, 0);

		g.drawText(title, 4, y, 0, w);

        g.setColor(Color.GREEN);
		g.drawText(source, 4, y + g.getFont().getHeight() + 2);
		g.setColor(Color.GRAY);
		g.drawText(pubDate + " ", 4, y + g.getFont().getHeight() + 2,
				DrawStyle.RIGHT, w);
		g.drawLine(4, y + g.getFont().getHeight()*2-1, getWidth(), y + g.getFont().getHeight()*2-1);
		g.setColor(Color.BLACK);
	}

	public Object get(ListField list, int index) {
		return _messgelist.elementAt(index);
	}

	public int indexOfList(ListField list, String prefix, int string) {
		return _messgelist.indexOf(prefix, string);
	}

	public int getPreferredWidth(ListField list) {
		return Display.getWidth();
	}

	private void navigationToMessageViewScreen() {
		MessageItem messageitem = (MessageItem) _messgelist.elementAt(getSelectedIndex());
		String html = ForwardBo.getMessageContent(messageitem.getId());
		MessageViewScreen screen = new MessageViewScreen();
		screen.initialize(html);
		UiApplication.getUiApplication().pushScreen(screen);
	}

	protected boolean navigationClick(int status, int time) {
		navigationToMessageViewScreen();
		return true;
	}

	protected boolean keyChar(char key, int status, int time) {
		if (key == Characters.ENTER) {
			navigationToMessageViewScreen();
		}
		return true;
	}
}
